/**
 * Global authority directive
 * Used for fine-grained control of component permissions
 * @Example v-access:role="[ROLE_NAME]" or v-access:role="ROLE_NAME"
 * @Example v-access:code="[ROLE_CODE]" or v-access:code="ROLE_CODE"
 */
import type { App, Directive } from 'vue';

import { checkBingShops } from '#/utils';

function isBindShop(el: any) {
  const handler = (event: any) => {
    if (!checkBingShops()) {
      event.stopPropagation();
      event.preventDefault();
    }
  };
  el.__hasPermissonHandler = handler;
  // 捕获阶段执行
  el.addEventListener('click', handler, true);
}
const mounted = (el: Element) => {
  isBindShop(el);
};

const authDirective: Directive = {
  mounted,
  unmounted(el) {
    const handler = el.__hasPermissonHandler;
    if (handler) {
      el.removeEventListener('click', handler);
      delete el.__hasPermissonHandler;
    }
  },

  // beforeMount: mounted,
};

export function registerBindShopDirective(app: App) {
  app.directive('bindshop', authDirective);
}
